﻿using MediatR;
using ProductionLine.API.Application.Command.Plan.Read;
using ProductionLine.Domain.Plan;
using ProductionLine.ErrorCode;
using ProductionLine.Extensions;
using ProductionLine.Infrastructure.Interface;

namespace ProductionLine.API.Application.Handler.Plan.Read
{
    public class GetPlanHandler : IRequestHandler<GetPlanCommand, APIPaging<List<PlanDTO>>>
    {
        IBaseRepository<PlanModel> planRepo;

        public GetPlanHandler(IBaseRepository<PlanModel> planRepo)
        {
            this.planRepo = planRepo;
        }

        public Task<APIPaging<List<PlanDTO>>> Handle(GetPlanCommand request, CancellationToken cancellationToken)
        {
            APIPaging<List<PlanDTO>> res=new APIPaging<List<PlanDTO>>();
            var lists=planRepo.GetAll().Where(c=>!c.IsDel);
            if(!string.IsNullOrEmpty(request.ProductName))
            {
                lists = lists.Where(c => c.ProductName.Contains(request.ProductName));
            }
            if(!string.IsNullOrEmpty(request.PlanCode))
            {
                lists = lists.Where(c => c.PlanCode.Contains(request.PlanCode));
            }
            if (request.PlanState != 0)
            {
                lists = lists.Where(c => c.PlanState == request.PlanState);
            }
            if (request.Resource != 0)
            {
                lists = lists.Where(c => c.Resource == request.Resource);
            }
            var linq = from a in lists
                       select new PlanDTO
                       {
                           PlanId = a.PlanId,
                           PlanName = a.PlanName,
                           PlanCode = a.PlanCode,
                           Resource = a.Resource,
                           ProductName = a.ProductName,
                           ProductCode = a.ProductCode,
                           Specification = a.Specification,
                           UnitName = a.UnitName,
                           PlanNum = a.PlanNum,
                           PlanStart = a.PlanStart,
                           PlanEnd = a.PlanEnd,
                           RequireDate = a.RequireDate,
                           PlanState = a.PlanState,
                           CreateDate = a.CreateDate,
                           CreateName = a.CreateName,
                           ProductId = a.ProductId,
                           State = a.State,
                           SalesOrderId = a.SalesOrderId,
                           IsDel = a.IsDel
                       };
            res.totalCount = linq.Count();
            res.totalPage = (int)Math.Ceiling(res.totalCount * 1.0 / request.pageSize);
            res.Data = linq.OrderByDescending(c => c.PlanId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            res.Msg = "查询生产计划成功";
            res.Code = APIEnum.Success;
            return Task.FromResult(res);
        }
    }
}
